<?php
/*********************************************************************\
*  Copyright (c) 1998-2013, TH. All Rights Reserved.
*  Author :lwj
*  FName  :Chuku.php
*  Time   :2019.10.22
*  Remark :成品出库管理
\*********************************************************************/
FLEA::loadClass('TMIS_Controller');
class Controller_Sample_Chuku  extends TMIS_Controller {

    /**
     * 操作和查询的权限id
     * @var 参数类型
    */
    var $editFuckId = '1-2';
    var $listFuckId = '1-2';

    /**
     * 入库类型编码前缀
     * @var 参数类型
    */
    var $codePrev = 'SC';
    function __construct() {
        $this->_modelExample = FLEA::getSingleton('Model_Sample_Chuku');
        $this->_subModel = FLEA::getSingleton('Model_Sample_Chuku2Product');
    }

    /**
     * 角色html配置form
     * Time：2018/12/13 15:49:40
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function _getMainFormItems() {
        $modelClient = FLEA::getSingleton('Model_Jichu_Client');
        $modelEmploy = FLEA::getSingleton('Model_Jichu_Employ');

        $mainFormItems = array(
            array(
                'type'       =>'comp-select',
                'name'       =>'clientId',
                'title'      =>'客户',
                'clearable'  =>true,
                'options'    =>$modelClient->getOptions(),
                'filterable' =>true,
                'multiple'   =>false
            ),
            array(
                'type'       =>'comp-select',
                'name'       =>'employId',
                'title'      =>'采样人',
                'clearable'  =>false,
                'options'    =>$modelEmploy->getEmploy(),
                'filterable' =>true,
                'multiple'   =>false
            ),
            array(
                'type'        =>'comp-text',
                'name'        =>'chukuCode',
                'title'       =>'出库单号',
                'readonly'    =>true,
                'clearable'   =>true,
                'value'       =>'',
                'placeholder' =>'系统自动生成，如：'.$this->createNewCode(),
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'creater',
                'title'     =>'操作人',
                'clearable' =>true,
                'readonly'  =>true,
                'value'     =>$_SESSION['REALNAME'],
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'reason',
                'title'     =>'原因',
                'clearable' =>true,
                'readonly'  =>false,
                'value'     =>'',
            ),
            array(
                'type'      =>'comp-calendar',
                'name'      =>'chukuDate',
                'title'     =>'出库日期',
                'clearable' =>true,
                'value'     =>date('Y-m-d'),
            ),
            array(
                'type'        =>'comp-textarea',
                'name'        =>'memo',
                'title'       =>'备注',
                'placeholder' =>'',
                'value'       =>'',
            ),
        );
        $sonFormItems[] = array(
                'title'        =>'样品明细',
                'key'          =>"Products",
                'buttonVisble' =>array(
                    'sonUpdown'  =>false,
                ),
                'items' => array(
                    array(
                        'type'       =>'comp-popup-select',
                        'name'       =>'productId',
                        'title'      =>'产品',
                        'value'      =>'',
                        'action'     =>url('Sample_Report','PopupSelect'),
                        'rowKey'     =>'productId',
                        'width'      =>'250',
                        'dialogWidth'=>'80%',
                        'displayKey' =>'productDesc',
                        'displayText'=>'',
                        'searchItems'=>array(
                            'proCode' =>'',
                            'proName' =>'',
                            'proDesc' =>'',
                            'barCode' =>'',
                        ),
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'proDesc',
                        'title'     =>'花型颜色',
                        'disabled'  =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'       =>'comp-text',
                        'name'       =>'type',
                        'title'      =>'样品类型',
                        'value'      =>'',
                        'clearable'  =>false,
                        'disabled'   =>true,
                        'width'      =>'100',
                    ),
                    array(
                        'type'       =>'comp-text',
                        'name'       =>'kuweiName',
                        'title'      =>'库位',
                        'value'      =>'',
                        'clearable'  =>false,
                        'disabled'   =>true,
                        'width'      =>'100',
                    ),
                    array(
                        'type'       =>'comp-text',
                        'name'       =>'kucun',
                        'title'      =>'库存数量',
                        'value'      =>'',
                        'clearable'  =>false,
                        'disabled'   =>true,
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'cnt',
                        'title'     =>'出库数量',
                        'clearable' =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'price',
                        'title'     =>'单价',
                        'clearable' =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-textarea',
                        'name'      =>'memoView',
                        'title'     =>'备注说明',
                        'clearable' =>true,
                        'value'     =>'',
                    ),
                )
            );

        $rules = array(
            'chukuDate'=>array(
                array('required'=>true,'message'=>'出库日期必须'),
            ),
            'employId'=>array(
                array('required'=>true,'message'=>'采样人必须'),
            ),
        );

        return array(
          'success'       =>true,
          'mainFormItems' =>$mainFormItems,
          'sonFormItems'  =>$sonFormItems,
          'rules'         =>$rules,
          'action'        =>$this->_url('Save'),
          'urlRemoveSon'  =>$this->_url('RemoveSonAjax'),
        );
    }

    /**
     * 创建入库的新编号
     * Time：2019/02/25 13:03:19
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function createNewCode(){
      $code = $this->_getNewCode($this->codePrev ,$this->_modelExample->tableName ,$this->_modelExample->codeField);
      return $code;
    }


    /**
     * @desc ：员工档案查询
     * Time：2017/07/31 15:45:28
     * @author li
    */
    function actionRight() {
        $this->authCheck($this->listFuckId);

        $searchItems = array(
            'dateRange' =>array(date('Y-m-d',mktime(0,0,0,date('m')-3,date('d'),date('Y'))),date('Y-m-d')),
            'barCode'   =>'',
            'proDesc'   =>'',
            'productId' =>'',
            'hzlId'     =>'',
            'kuweiId'   =>array(),
            'clientId'  =>array(),
            'employId'  =>array(),
        );

        $smarty = & $this->_getView();

        $editButtons = array(
            array('text'=>'修改','type'=>'redirect','icon'=>'el-icon-edit','options'=>array(
                'url'            =>$this->_url('Edit').'&id={chukuId}',
                'disabledColumn' =>'__disabledEdit',
            )),
            array('text'=>'删除整个出库单数据','type'=>'remove','options'=>array(
                'url'            =>$this->_url('RemoveSonAjaxList'),
                'disabledColumn' =>'__disabledRemove',
            )),
            array('text'=>'打印标签','type'=>'redirect','icon'=>'el-icon-printer','options'=>array(
                'url'            =>$this->_url('Print').'&id={chukuId}',
                'disabledColumn' =>'__disabledPrint',
            )),
        );

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();
        // foreach ($fileds as & $fv) {
        //     $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        // }
        $arrFieldInfo = array_merge(
            array(
                "chukuDate"  =>array('text'=>"出库日期",'width'=>'110','editButtons'=>$editButtons,'showButton'=>true),
                "chukuCode"  =>array('text'=>"出库单号",'width'=>'120'),
                "clientName" =>array('text'=>"客户",'width'=>'100'),
                "employName" =>array('text'=>"采样人",'width'=>'100'),
                "kindName"   =>array('text'=>"产品类别",'width'=>'100'),
                "code"       =>array('text'=>"产品编号",'width'=>'100'),
                "proName"    =>array('text'=>"产品名称",'width'=>'120'),

            )
            ,$fileds
            ,array(
                "proDesc"    =>array('text'=>"花型颜色",'width'=>'100','forKeySearch'=>true),
                "type"       =>array('text'=>"样品类型",'width'=>'90','forKeySearch'=>true),
                "cnt"        =>array('text'=>"数量",'width'=>'70'),
                "gexing"     =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"      =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"      =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"        =>array('text'=>"后整理工艺",'width'=>'100'),
                "kuweiName"  =>array('text'=>"库位",'width'=>'100'),
                'price'      => array('text'=>'单价','width'=>'100'),
                'money'      => array('text'=>'金额','width'=>'100'),
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                "creater"   =>array('text'=>"操作人",'width'=>'100'),
                "memoView"  =>array('text'=>"备注",'width'=>''),
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('actionLoadData', $this->_url('GetRows'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('colsForKey', array(
            array('text' =>'产品编号','col'=>'proCode'),
            array('text' =>'产品名称','col'=>'proName'),
            // array('text' =>'规格','col'=>'guige'),
            array('text' =>'格型','col'=>'gexing'),
            array('text' =>'组织','col'=>'zuzhi'),
            array('text' =>'花型颜色','col'=>'proDesc'),
        ));

        // $smarty->assign('addUrl',$this->_url('Add'));
        $smarty->assign('menuRightTop', array(
            array('text'=>'新增出库','icon'=>'el-icon-plus','url'=>$this->_url('Add')),
            array('text'=>'扫码出库','icon'=>'el-icon-plus','url'=>url('Sample_SmChuku','Add')),
        ));

        $smarty->display('Async/TableList.tpl');
    }

    /**
     * @desc ：员工档案查询
     * Time：2017/07/31 15:45:28
     * @author li
    */
    function actionReportViewList() {
        $this->authCheck(0);

        $dateFrom = $_GET['dateFrom'] ? $_GET['dateFrom'] : date('Y-m-01');
        $dateTo = $_GET['dateTo'] ? $_GET['dateTo'] : date('Y-m-d');
        $searchItems = array(
            'dateRange' =>array($dateFrom, $dateTo),
            'proDesc'   =>$_GET['proDesc'].'',
            'productId' =>$_GET['productId'],
            'kuweiId'   =>array($_GET['kuweiId']),
            'type'      =>array($_GET['type']),
            'barCode'   =>$_GET['code'].'',
            'clientId'  =>array($_GET['clientId']),
            'employId'  =>array($_GET['employId']),
        );


        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2Table();
        foreach ($fileds as & $fv) {
            $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        }
        $arrFieldInfo = array_merge(
            array(
                "chukuDate"  =>array('text'=>"出库日期",'width'=>'110'),
                "chukuCode"  =>array('text'=>"出库单号",'width'=>'120'),
                "clientName" =>array('text'=>"客户",'width'=>'100'),
                "employName" =>array('text'=>"采样人",'width'=>'100'),
                "kindName"   =>array('text'=>"产品类别",'width'=>'100'),
                "code"       =>array('text'=>"条码",'width'=>'100'),
                "proCode"    =>array('text'=>"产品编号",'width'=>'100'),
                "proName"    =>array('text'=>"产品名称",'width'=>'100'),
                "proDesc"    =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
                "type"       =>array('text'=>"样品类型",'width'=>'100','forKeySearch'=>true),
                "gexing"    =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"     =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"     =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"       =>array('text'=>"后整理工艺",'width'=>'100'),
                "cnt"        =>array('text'=>"数量",'width'=>'70'),
                "kuweiName"  =>array('text'=>"库位",'width'=>'100'),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                "creater"   =>array('text'=>"操作人",'width'=>'100'),
                "memoView"  =>array('text'=>"备注",'width'=>'150'),
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetRows'));
        $smarty->assign('searchItems', $searchItems);

        // $smarty->assign('addUrl',$this->_url('Add'));
        // $smarty->assign('menuRightTop', array(
        //     array('text'=>'新增(不关联制作单)','url'=>$this->_url('Add')),
        // ));
        // $smarty->assign('sonTpl',array(
        //     'Jichu/TableProductList.js'
        // ));
        $smarty->assign('ignoreSearchCache',true);

        $smarty->display('TableList_v1.1.tpl');
    }

    /**
     * 获取计划任务的数据
     * @author li
    */
    public function actionGetRows() {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }
        FLEA::loadClass('TMIS_Common');

        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        $sql="SELECT x.*,y.chukuDate,y.chukuCode,y.reason,y.creater,y.employId,y.clientId,y.memo
              from sample_chuku2product x
              left join sample_chuku y on y.id=x.chukuId
              left join jichu_product p on p.id=x.productId
              where 1 ";

        // 按照采样人限制查看对应的数据
        $mUser = FLEA::getSingleton('Model_Acm_User');
        $traderArr = $mUser->getTraderIdByUser($_SESSION['USERID']);
        if($traderArr['_ALL_'] == false){
            $traderIds = join(',',$traderArr['Traders']);
            !$traderIds && $traderIds = '-1';
            $sql .= " and y.employId in ({$traderIds})";
        }

        if($arr['chukuCode']!='') {
            $sql.=" and y.chukuCode like '%{$arr['chukuCode']}%'";
        }
        if($arr['type']) {
            foreach ($arr['type'] as & $a) {
                $a = "'{$a}'";
            }
            $type = join(',' ,$arr['type']);
            $sql.=" and x.type in ({$type})";
        }
        if($arr['clientId']) {
            $clientId = join(',' ,$arr['clientId']);
            $sql.=" and y.clientId in ({$clientId})";
        }
        if($arr['employId']) {
            $employId = join(',' ,$arr['employId']);
            $sql.=" and y.employId in ({$employId})";
        }
        if($arr['proDesc']!='') {
            $sql.=" and x.proDesc like '%{$arr['proDesc']}%'";
        }
        if($arr['gexing']!='') {
            $sql.=" and x.gexing like '%{$arr['gexing']}%'";
        }
        if($arr['zuzhi']!='') {
            $sql.=" and x.zuzhi like '%{$arr['zuzhi']}%'";
        }
        // if($arr['tanli']!='') {
        //     $sql.=" and x.tanli like '%{$arr['tanli']}%'";
        // }
        if($arr['hzlId']!='') {
            $sql.=" and find_in_set({$arr['hzlId']} ,`hzlId`)";
        }
        if($arr['barCode']!='') {
            $sql.=" and x.code like '%{$arr['barCode']}%'";
        }
        if($arr['reason']!='') {
            $sql.=" and y.reason like '%{$arr['reason']}%'";
        }
        if($arr['proName']!='') {
            $sql.=" and p.proName like '%{$arr['proName']}%'";
        }
        if($arr['proCode']!='') {
            $sql.=" and p.proCode like '%{$arr['proCode']}%'";
        }
        if($arr['guige']!='') {
            $sql.=" and p.guige like '%{$arr['guige']}%'";
        }
        if($arr['productId']) {
            $sql.=" and x.productId = '{$arr['productId']}'";
        }
        if($arr['kuweiId']) {
            $kuweiId = join(',' ,$arr['kuweiId']);
            $sql.=" and x.kuweiId in ({$kuweiId})";
        }
        if($arr['dateRange']){
            list($datefrom ,$dateTo) = $arr['dateRange'];
            $sql .= " and y.chukuDate >= '{$datefrom}' and y.chukuDate <= '{$dateTo}'";
        }
        $sql .=" order by y.id desc,x.id asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelClient = FLEA::getSingleton('Model_Jichu_Client');
        $modelEmploy = FLEA::getSingleton('Model_Jichu_Employ');
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            // dump($tmp);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);

            $v['money'] = round($v['price']*$v['cnt'],2);
            $v['cnt'] = round($v['cnt'],3);
            $v['price'] = round($v['price'],2);

            if($v['kuweiId']){
                $_tmp = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $_tmp['kuweiName'];
            }

            if($v['clientId']){
                $_tmp = $modelClient->find($v['clientId']);
                $v['clientName'] = $_tmp['compName'];
            }

            if($v['employId']){
                $_tmp = $modelEmploy->find($v['employId']);
                $v['employName'] = $_tmp['employName'];
            }

            // 查找后整理工艺
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }

            //有小备注显示小备注,没有则显示大备注
            $v['memoView'] = $v['memoView'] ? $v['memoView'] : $v['memo'];
        }

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;
    }


     /**
     * 新增
     * Time：2018/12/17 13:35:37
     * @author li
    */
    function actionAdd() {
        $this->authCheck($this->editFuckId);
        $this->_edit(array());
    }

    function actionEdit(){
        $this->authCheck($this->editFuckId);

        // 单条修改
        $row = $this->_modelExample->find($_GET['id']);
        // dump($row);exit;
        $this->_edit($row);
    }

    function _edit($Arr = array() ,$fromAction) {
        $Arr['fromAction'] = $fromAction;

        if(!$Arr['Products']){
            $Arr['Products'] = array();
        }

        //处理档案
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
        foreach ($Arr['Products'] as & $v) {
            //查找产品档案的信息
            if($v['productId']){
                $sql = "select x.*,y.kindName from jichu_product x
                    left join jichu_prokind y on x.kindId=y.id
                  where x.id = '{$v['productId']}'";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['productDesc'] = $v['code'].'-'.$tmp[0]['kindName'].'-'.$tmp[0]['proName'];
            }
            if($v['kuweiId']){
                $tmp = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $tmp['kuweiName'];
            }

            //查找对应的库存数量
            $kucun = $modelKucun->getKucun(array(
                'productId' =>$v['productId'],
                'type'      =>$v['type'],
                'proDesc'   =>$v['proDesc'],
                'kuweiId'   =>$v['kuweiId'],
            ));
            $v['kucun'] = $kucun+$v['cnt'];
        }
        // dump($Arr);exit;

        $smarty = & $this->_getView();
        $smarty->assign('title','基本信息');
        $smarty->assign('row',$Arr);
        $smarty->assign('sonTpl','Sample/SampleChuku.js');
        $smarty->assign('formItems',$this->_getMainFormItems());
        $smarty->display('Async/MainSonForm.tpl');
    }

    /**
     * 档案保存
     * Time：2017/07/31 15:48:32
     * @author li
    */
    function actionSave() {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array('msg'=>'登录权限过期','success'=>false);
            echo json_encode($ret);exit;
        }
        $post = $this->axiosPost();
        if(!$post['chukuCode']){
            $post['chukuCode'] = $this->createNewCode();
        }
        !$post['creater'] && $post['creater'] = $_SESSION['REALNAME'];

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $codeNext = 0;
        foreach ($post['Products'] as $key => &$v) {
            //如果没有数量或者材料Id,则跳过
            if(!$v['productId']){
                unset($post['Products'][$key]);
            }
            // if(!$v['kuweiId']){
            //     $ret = array('msg'=>'第'.($key+1).'行有误，请确认选择库位','success'=>false);
            //     echo json_encode($ret);exit;
            // }
            if(!$v['cnt']){
                $ret = array('msg'=>'第'.($key+1).'行有误，请确认填写数量','success'=>false);
                echo json_encode($ret);exit;
            }
            if($v['cnt'] > $v['kucun']){
                $ret = array('msg'=>'第'.($key+1).'行有误，出库数量不能大于库存数量','success'=>false);
                echo json_encode($ret);exit;
            }

            // 通过条码，获取最近一次的格型等信息
            if($v['code']){
                $sql = "SELECT * from sample_ruku2product where code='{$v['code']}' order by id desc limit 0,1";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['gexing'] = $tmp[0]['gexing'].'';
                $v['zuzhi']  = $tmp[0]['zuzhi'].'';
                $v['tanli']  = $tmp[0]['tanli'].'';
                $v['hzlId']  = $tmp[0]['hzlId'].'';
            }
            unset($v['id']);unset($v['rukuId']);continue;
        }

        if(!$post['Products']){
            $ret = array('msg'=>'无有效明细信息','success'=>false);
            echo json_encode($ret);exit;
        }
        //数据保存
        $result = $this->_modelExample->save($post);
        if($post['flag']){
            $targetUrl = $this->_url('Print').'&id='.$result;
        }else{
            $targetUrl = $this->_url($targetUrl ? $targetUrl : 'Right');
        }
        // dump($result);exit;
        if($result){
            $ret = array(
                'success'   =>true,
                'msg'       =>'操作成功',
                'targetUrl' =>$targetUrl,
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'操作失败',
            );
        }

        echo json_encode($ret);exit;
    }

    function actionRemoveSonAjaxList(){
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);
        $id = intval($_POST['row']['id']);

        $row = $this->_subModel->find($id);
        if($row['chukuId']){
          $res = $this->_modelExample->removeByPkv($row['chukuId']);
        }

        if($res){
            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    function actionRemoveAjax() {
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);
        $id = intval($_POST['row']['id']);

        $res = $this->_modelExample->removeByPkv($id);

        if($res){
            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    function actionRemoveSonAjax() {
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);
        $id = intval($_POST['row']['id']);


        $res = $this->_subModel->removeByPkv($id);

        if($res){
            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    /**
     * 打印标签
     * Time：2019/10/24 17:04:44
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionPrint(){
        //每个产品分类的标签配置不一样，所以先获取配置，如果没有配置需要提醒需要先配置
        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $_modelPro = FLEA::getSingleton('Model_Jichu_Product');
        $_modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $_modelPrintConfig = FLEA::getSingleton("Model_Jichu_PrintConfig");
        $chukuId = $_GET['id'] ? $_GET['id'] : '-1';

        $sql = "SELECT x.*,y.chukuDate as `date`
            from sample_chuku2product x
            left join sample_chuku y on x.chukuId=y.id
            where y.id in({$chukuId})";
        $chukuInfo = $this->_modelExample->findBySql($sql);
        $allKind = $_modelKind->findAll();
        // dump($allKind);die;
        foreach ($allKind as $k => & $v) {
            $sql = "SELECT * FROM jichu_prokind_print_config where kindId = '{$v['id']}'";
            $tmp = $_modelPrintConfig->findBySql($sql);
            $v['printConfig'] = $tmp[0]['printConfig'];
        }
        // //标题映射
        // $titleConfig = array(
        //     'chinese'           =>'title',
        //     'english'           =>'titleEng',
        //     'chineseAndEnglish' =>'title,titleEng',
        // );

        // //花型颜色的标题
        // $_tR = array(
        //     'proDesc'=>array(
        //         'chinese'           =>'颜色',
        //         'english'           =>'Detail',
        //         'chineseAndEnglish' =>'颜色/Detail',
        //     ),
        //     'gexing'=>array(
        //         'chinese'           =>'格型',
        //         'english'           =>'Pattern',
        //         'chineseAndEnglish' =>'格型/Pattern',
        //     ),
        //     'zuzhi'=>array(
        //         'chinese'           =>'组织',
        //         'english'           =>'Construction',
        //         'chineseAndEnglish' =>'组织/Construction',
        //     ),
        //     'hzl'=>array(
        //         'chinese'           =>'后整理',
        //         'english'           =>'Finish',
        //         'chineseAndEnglish' =>'后整理/Finish',
        //     ),
        //     'kuweiName'=>array(
        //         'chinese'           =>'库位',
        //         'english'           =>'Location',
        //         'chineseAndEnglish' =>'库位/Location',
        //     ),
        // );

        // $_tP = array(
        //     'proName'=>array(
        //         'chinese'           =>'名称',
        //         'english'           =>'Name',
        //         'chineseAndEnglish' =>'名称/Name',
        //     ),
        //     'proCode'=>array(
        //         'chinese'           =>'编号',
        //         'english'           =>'No.',
        //         'chineseAndEnglish' =>'编号/No.',
        //     ),
        // );

        // $_detialTitle = array_merge($_tR ,$_tP);

        //花型颜色的标题
        $_tR = array('proDesc','gexing','zuzhi','hzl','kuweiName','remark','date');

        $_tP = array('proName','proCode');

        $_detialTitle = array_merge($_tR ,$_tP);

        //处理配置的信息，把需要打印的配置整理成下面需要的格式
        $_config = array();
        foreach ($allKind as $key => & $v) {
            $v['fields'] = $v['extendAttr'] ? json_decode($v['extendAttr'] ,true) : array();
            foreach ($v['PrintCfg'] as $k => & $va) {
                $v['print'][] = $va ? json_decode($va['printConfig'] ,true) : array();
                $v['print'][$k]['id'] = $va['id'];
                $v['print'][$k]['isDefault'] = $va['isDefault'];
            }
            $_config[$v['id']] = $v['print'];
        }
        // dump($_config);die;
        // //处理配置的信息，把需要打印的配置整理成下面需要的格式
        // $_config = array();
        // foreach ($allKind as $key => & $v) {
        //     $v['fields'] = $v['extendAttr'] ? json_decode($v['extendAttr'] ,true) : array();
        //     $v['print'] = $v['printConfig'] ? json_decode($v['printConfig'] ,true) : array();
        //     // dump($v);exit;
        //     //先确认标题显示的内容
        //     $show = array();
        //     $_tTmp = explode(',' ,$titleConfig[$v['print']['language']]);
        //     // dump($v);
        //     //先给标题加个中英文的
        //     if(!$v['print']){
        //         continue;
        //     }
        //     foreach ($v['fields'] as & $f) {
        //         $tmp = array();
        //         $tmp[] = $f['title'];
        //         $f['titleEng'] && $tmp[] = $f['titleEng'];
        //         $f['chinese'] = $f['title'];
        //         $f['english'] = $f['titleEng'] ? $f['titleEng'] : '未配置';
        //         $f['chineseAndEnglish'] = join('/' ,$tmp);
        //         // dump($f);
        //         //开始处理配置中的信息
        //         foreach($v['print']['fileds'] as & $f2) {
        //             //花型颜色的标题
        //             if(array_key_exists(trim($f2) ,$_detialTitle)){
        //                 $tmp = array(
        //                     'filed'=>$f2,
        //                     'title'=>$_detialTitle[trim($f2)][$v['print']['language']],
        //                 );
        //                 $f2 = $tmp;
        //             }

        //             if(trim($f2) == trim($f['filed'])){
        //                 $tmp = array(
        //                     'filed'=>$f['filed'],
        //                     'title'=>$f[$v['print']['language']],
        //                 );
        //                 $f2 = $tmp;
        //             }
        //         }
        //         // dump($v['print']);
        //     }

        //     $_config[$v['id']] = $v['print'];
        // }
        // dump($_config);

        //遍历产品信息，循环获取需要打印的标签有哪些，打印页面还要确认打印的数量
        $printPage = array();
        foreach ($chukuInfo as $key => & $v) {
            //处理每个产品需要打印的格式和排版
            $_product = $_modelPro->find($v['productId']);
            $v['Product'] = $_product;

            $_kuwei = $_modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_kuwei['kuweiName'];

            // 查找后整理
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }

            //如果没有配置打印，则显示无配置
            if(!isset($_config[$_product['kindId']])){
                $v['Print'] = array(
                    // 'error'=>'该分类未配置标签打印格式'
                );
                continue;
            }

            //把配置中的信息放到数据中
            $v['Print'] = $_config[$_product['kindId']];
            //打印内容
            $v['objectData'] = array();

            // //把需要展示的value字段找到
            foreach ($v['Print'] as $k => & $va) {
                foreach ($va['fileds'] as & $p) {
                    if(in_array($p, $_tR)){
                        $va['objectData'][$p] = strval($v[$p]).'';
                    }else{
                        $va['objectData'][$p] = $_product[$p].'';
                    }
                    $va['objectData']['code'] = $v['code'];
                }
                $va['objectData']['proCode'] = $v['code'];
            }
            // //把需要展示的value字段找到
            // foreach ($v['Print']['fileds'] as & $p) {
            //     if(isset($_tR[$p['filed']])){
            //         $p['value'] = strval($v[$p['filed']]).'';
            //     }else{
            //         $p['value'] = $_product[$p['filed']].'';
            //     }
            // }

            // // 格式化高级打印排版的数据结构
            // foreach ($v['Print']['fileds'] as & $p) {
            //     $v['Print']['filedList'][$p['filed']] = $p;
            // }
            // $v['Print']['compName'] = $sys['compName'];
            // $v['Print']['code'] = $v['code'];
        }
        // dump($chukuInfo);exit;
        //打印标签
        $smarty = & $this->_getView();
        $smarty->assign('row',$chukuInfo);
        $smarty->assign('sys',$sys);
        $smarty->display('Sample/PrintCode.tpl');
    }
}

?>